//
//  PopoverView.m
//  ArrowView
//
//  Created by guojiang on 4/9/14.
//  Copyright (c) 2014年 LINAICAI. All rights reserved.
//

#import "MyPoperView.h"


#define kArrowHeight 10.f
#define kArrowCurvature 6.f
#define SPACE 2.f
#define ROW_HEIGHT 36.f
#define TITLE_FONT [UIFont systemFontOfSize:13]
#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

@interface MyPoperView ()<UITableViewDataSource, UITableViewDelegate>
{
    BOOL isAnimationFinished;
}
@property (nonatomic) CGPoint showPoint;

@property (nonatomic, strong) UIButton *handerView;

@end

@implementation MyPoperView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.borderColor = [ClassMethodsViewController colorWithHexString:BORDERCOLOR];
        self.backgroundColor = [UIColor clearColor];
        isAnimationFinished = YES;
    }
    return self;
}

-(id)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray *)images
{
    self = [super init];
    if (self) {
        self.showPoint = point;
        self.titleArray = titles;
        self.imageArray = images;
        
        self.frame = [self getViewFrame];
        
        [self addSubview:self.tableView];
        
    }
    return self;
}

-(id)initWithPoint:(CGPoint)point titles:(NSArray *)titles images:(NSArray *)images selectImage:(NSArray *)selectImages
{
    self = [super init];
    if (self) {
        self.showPoint = point;
        self.titleArray = titles;
        self.imageArray = images;
        self.selectImageArray = [selectImages isEqual:[NSNull null]] ? nil : selectImages;
        
        self.frame = [self getViewFrame];
        
        [self addSubview:self.tableView];
        
    }
    return self;
}

-(id)initWithPoint:(CGPoint)point titlesDict:(NSDictionary *)titlesDict imagesDict:(NSDictionary *)imagesDict{
    self = [super init];
    if (self) {
        self.showPoint = point;
        
    }
    return self;
}


-(CGRect)getViewFrame
{
    CGRect frame = CGRectZero;
    
    NSInteger totalRow = 0;
    for (NSInteger i=0; i<self.titleArray.count; i++) {
        totalRow += ((NSArray *)[self.titleArray objectAtIndex:i]).count;
    }
    
    frame.size.height = totalRow * ROW_HEIGHT + SPACE + kArrowHeight;
    if (frame.size.height > 200) {
        frame.size.height = 200;
    }
    
    for (NSInteger i=0; i<self.titleArray.count; i++) {
        for (NSString *title in [self.titleArray objectAtIndex:i]) {
            CGFloat width =  [title sizeWithFont:TITLE_FONT constrainedToSize:CGSizeMake(300, 100) lineBreakMode:NSLineBreakByCharWrapping].width;
            frame.size.width = MAX(width, frame.size.width);
        }
    }

    if ([self.titleArray count] == [self.imageArray count]) {
        frame.size.width = 10 + 25 + 10 + frame.size.width + 40;
    }else{
        frame.size.width = 10 + frame.size.width + 40;
    }
    
    frame.origin.x = self.showPoint.x - frame.size.width/2;
    frame.origin.y = self.showPoint.y;
    
    //左间隔最小5x
    if (frame.origin.x < 5) {
        frame.origin.x = 5;
    }
    //右间隔最小5x
    if ((frame.origin.x + frame.size.width) > kScreenWidth-5) {
        frame.origin.x = kScreenWidth - 5 - frame.size.width;
    }
    
    return frame;
}


-(void)show
{
    if (isAnimationFinished == YES) {
        isAnimationFinished = NO;

        self.handerView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_handerView setFrame:[UIScreen mainScreen].bounds];
        [_handerView setBackgroundColor:[UIColor clearColor]];
        [_handerView addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        [_handerView addSubview:self];
        UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
        [window addSubview:_handerView];
    
        CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
        self.layer.anchorPoint = CGPointMake(arrowPoint.x / self.frame.size.width, arrowPoint.y / self.frame.size.height);
        self.frame = [self getViewFrame];
    
        self.alpha = 0.f;
        self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
        [UIView animateWithDuration:0.2f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.transform = CGAffineTransformMakeScale(1.05f, 1.05f);
            self.alpha = 1.f;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.08f delay:0.f options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                isAnimationFinished = YES;
            }];
        }];
    }
}

-(void)dismiss
{
    [self dismiss:YES];
}

-(void)dismiss:(BOOL)animate
{
    if (isAnimationFinished == YES) {
        isAnimationFinished = NO;
        if (!animate) {
            [_handerView removeFromSuperview];
            return;
        }
        
        [UIView animateWithDuration:0.3f animations:^{
            self.transform = CGAffineTransformMakeScale(0.1f, 0.1f);
            self.alpha = 0.f;
        } completion:^(BOOL finished) {
            isAnimationFinished = YES;
            [_handerView removeFromSuperview];
        }];
    }
}


#pragma mark - UITableView

-(UITableView *)tableView
{
    if (_tableView != nil) {
        return _tableView;
    }
    
    CGRect rect = self.frame;
    rect.origin.x = SPACE;
    rect.origin.y = kArrowHeight + SPACE;
    rect.size.width -= SPACE * 2;
    rect.size.height -= (SPACE * 2 + kArrowHeight);
//    rect.size.height -= (SPACE - kArrowHeight);
    
    self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.alwaysBounceHorizontal = NO;
    _tableView.alwaysBounceVertical = YES;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = YES;
    _tableView.scrollEnabled = YES;
    _tableView.backgroundColor = [UIColor clearColor];
    //    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    return _tableView;
}

#pragma mark - UITableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ((NSArray *)[self.titleArray objectAtIndex:section]).count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        return 1;
    }
    return 0.01;
}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return 0.01;
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        UIView *aView = [[UIView alloc]init];
        aView.backgroundColor = UIColorFromRGB(0xcccccc);
        return aView;
    }
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.textColor = [UIColor whiteColor];
    
    cell.textLabel.textColor = [ClassMethodsViewController colorWithHexString:TEXT_COLOR];

    cell.backgroundView = [[UIView alloc] init];
    cell.selectedBackgroundView.backgroundColor = [ClassMethodsViewController colorWithHexString:LEFT_SELECT_BACKCOLOR];
    cell.backgroundView.backgroundColor =  [ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16];
    
    if ([_imageArray count] == [_titleArray count]) {
        cell.imageView.image = [UIImage imageNamed:[_imageArray objectAtIndex:indexPath.row]];
    }
    if ([_selectImageArray count] == [_titleArray count]) {
        cell.imageView.highlightedImage = [UIImage imageNamed:[_selectImageArray objectAtIndex:indexPath.row]];
    }
    cell.textLabel.font = TITLE_FONT;
    cell.textLabel.text = [((NSArray *)[self.titleArray objectAtIndex:indexPath.section]) objectAtIndex:indexPath.row];
    
    cell.textLabel.highlightedTextColor= [ClassMethodsViewController colorWithHexString:SELECT_BORDERCOLOR];

    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    return cell;
}

#pragma mark - UITableView Delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.selectRowAtIndex) {
        self.selectRowAtIndex(indexPath);
    }
    [self dismiss:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ROW_HEIGHT;
}



// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    [self.borderColor set]; //设置线条颜色
    
    CGRect frame = CGRectMake(0, 10, self.bounds.size.width, self.bounds.size.height - kArrowHeight);
    
    float xMin = CGRectGetMinX(frame);
    float yMin = CGRectGetMinY(frame);
    
    float xMax = CGRectGetMaxX(frame);
    float yMax = CGRectGetMaxY(frame);
    
    CGPoint arrowPoint = [self convertPoint:self.showPoint fromView:_handerView];
    
    UIBezierPath *popoverPath = [UIBezierPath bezierPath];
    [popoverPath moveToPoint:CGPointMake(xMin, yMin)];//左上角
    
    /********************向上的箭头**********************/
    [popoverPath addLineToPoint:CGPointMake(arrowPoint.x - kArrowHeight+4, yMin)];//left side1
    [popoverPath  addCurveToPoint:CGPointMake(arrowPoint.x + kArrowHeight-2, yMin) controlPoint1:CGPointMake(arrowPoint.x+4, 0) controlPoint2:CGPointMake(arrowPoint.x, 0)];
    [popoverPath addLineToPoint:CGPointMake(xMax, yMin)];

    /********************向上的箭头**********************/
    
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMin)];//右上角
    
    [popoverPath addLineToPoint:CGPointMake(xMax, yMax)];//右下角
    
    [popoverPath addLineToPoint:CGPointMake(xMin, yMax)];//左下角
    
    //填充颜色
    [ [ClassMethodsViewController colorWithHexString:LEFT_BACKCOLOR_16] setFill];
    [popoverPath fill];
    
    [popoverPath closePath];
    [popoverPath stroke];
}


@end
